<script setup lang="ts">
import { getAddressDetailAPI, postMemberAddressAPI, putMemberAddressAPI } from '@/services/address'
import type { AddressParams } from '@/types/address'
import { ref } from 'vue'

// 表单数据
const form = ref<AddressParams>({
  receiver: '', // 收货人
  contact: '', // 联系方式
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0 // 默认地址，1为是，0为否
})

// 表单实例
const formRef = ref<UniHelper.UniFormsInstance>()

// 表单校验规则
const rules = {
  receiver: {
    rules: [
      { required: true, errorMessage: '请输入收货人姓名' },
      { minLength: 2, maxLength: 20, errorMessage: '收货人姓名长度在2-20个字符之间' }
    ]
  },
  contact: {
    rules: [
      { required: true, errorMessage: '请输入联系方式' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
    ]
  },
  countyCode: {
    rules: [{ required: true, errorMessage: '请选择所在地区' }]
  },
  address: {
    rules: [
      { required: true, errorMessage: '请输入详细地址' },
      { minLength: 5, maxLength: 100, errorMessage: '详细地址长度在5-100个字符之间' }
    ]
  }
}

// #ifdef MP-WEIXIN
// 地区选择
// 省市区(前端展示)
const fullLocation = ref('')
const onRegionChange = (ev: UniHelper.RegionPickerOnChangeEvent) => {
  fullLocation.value = ev.detail.value.join(' ') // 省市区(前端展示)
  // 保存地区编码
  const [provinceCode, cityCode, countyCode] = ev.detail.code!
  // 将地区编码赋值给 form 对象
  Object.assign(form.value, { provinceCode, cityCode, countyCode })
}
// #endif

// #ifdef H5 || APP-PLUS
// 地区选择
const onPickAppChange: UniHelper.UniDataPickerOnChange = (ev) => {
  console.log(ev.detail.value)
  // 保存地区编码
  const [provinceCode, cityCode, countyCode] = ev.detail.value.map((item) => item.value)
  // 将地区编码赋值给 form 对象
  Object.assign(form.value, { provinceCode, cityCode, countyCode })
}
// #endif

// 编辑 ------------------------------------------------
const props = defineProps<{
  id: string
}>()

// 获取地址详情
const getAddressDetail = async () => {
  const res = await getAddressDetailAPI(props.id)
  // 回显数据
  form.value.receiver = res.result.receiver
  form.value.contact = res.result.contact
  form.value.provinceCode = res.result.provinceCode
  form.value.cityCode = res.result.cityCode
  form.value.countyCode = res.result.countyCode
  form.value.address = res.result.address
  form.value.isDefault = res.result.isDefault
}
if (props.id) {
  getAddressDetail()
}

// 保存地址 ------------------------------------------------
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value?.validate?.()
    // 提交表单
    if (!props.id) {
      // 新增
      await postMemberAddressAPI(form.value)
      uni.showToast({ icon: 'success', title: '添加成功' })
    } else {
      // 编辑
      await putMemberAddressAPI(props.id, form.value)
      uni.showToast({ icon: 'success', title: '修改成功' })
    }
    setTimeout(() => {
      uni.navigateBack()
    }, 400)
  } catch (err) {
    uni.showToast({ icon: 'error', title: '请填写完整信息' })
  }
}
</script>

<template>
  <view class="content">
    <uni-forms
      class="form"
      :model="form"
      :rules="rules"
      ref="formRef"
      validate-trigger="submit"
      label-position="left"
      label-width="200rpx"
    >
      <uni-forms-item label="收货人" name="receiver">
        <input class="input" placeholder="请填写收货人姓名" v-model="form.receiver" />
      </uni-forms-item>
      <uni-forms-item label="手机号码" name="contact">
        <input class="input" placeholder="请填写收货人手机号码" v-model="form.contact" />
      </uni-forms-item>
      <uni-forms-item label="所在地区" name="countyCode">
        <!-- 地区选择器 -->
        <!-- #ifdef MP-WEIXIN -->
        <picker
          class="picker"
          mode="region"
          :value="fullLocation.split(' ')"
          @change="onRegionChange"
        >
          <view v-if="fullLocation">{{ fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
        <!-- #endif -->

        <!-- #ifdef H5 || APP-PLUS -->
        <uni-data-picker
          placeholder="请选择地址"
          popup-title="请选择城市"
          collection="opendb-city-china"
          field="code as value, name as text"
          orderby="value asc"
          :step-searh="true"
          self-field="code"
          parent-field="parent_code"
          :clear-icon="false"
          @change="onPickAppChange"
          v-model="form.countyCode"
        >
        </uni-data-picker>
        <!-- #endif -->
      </uni-forms-item>
      <uni-forms-item label="详细地址" name="address">
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </uni-forms-item>
      <uni-forms-item label="设为默认地址">
        <switch
          class="switch"
          color="#27ba9b"
          :checked="form.isDefault === 1"
          @change="(ev) => (form.isDefault = ev.detail.value ? 1 : 0)"
        />
      </uni-forms-item>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @click="onSubmit">保存并使用</button>
</template>

<style lang="scss">
:deep(.selected-area) {
  height: auto !important;
  flex: 0 0 auto !important;
}

:deep(.arrow-area) {
  display: none !important;
}

:deep(.selected-area.placeholder > span) {
  font-size: 30rpx !important;
}

:deep(.input-value-border[data-v-49f4f0fe]) {
  border: 0px !important;
}

page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx 40rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
      align-items: center;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>
